package com.rxnetwork.sample.mvp

import android.app.Dialog
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.LinearLayout
import com.rxnetwork.sample.R
import com.rxnetwork.sample.mvp.toolbar.BaseTopBarActivity
import com.rxnetwork.sample.utils.network.AppNetWorkManager
import java.lang.reflect.ParameterizedType

abstract class MVPBaseActivity<V : BaseView, T : BasePresenterImpl<V>> : BaseTopBarActivity(), BaseView {
    var mPresenter: T? = null

    var mViewLoading: Dialog? = null

    private fun getmViewLoading(): Dialog? {
        if (mViewLoading == null) {
            mViewLoading = Dialog(this)
            val dialogView = LayoutInflater.from(this).inflate(R.layout.loading, null)
            mViewLoading?.setContentView(dialogView)
            val dialogWindow = mViewLoading?.window
            dialogWindow?.setGravity(Gravity.CENTER)
            dialogWindow?.setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
            mViewLoading?.setCanceledOnTouchOutside(false)
            mViewLoading?.setCancelable(false)
        }
        return mViewLoading
    }

    override fun initPresenter() {
        mPresenter = getInstance<T>(this, 1)
        mPresenter?.attachView(this as V)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mPresenter != null) {
            mPresenter?.detachView()
            mPresenter = null
        }
        //取消网络
        AppNetWorkManager.instance?.clearSubscription()
    }

    val context: Context
        get() = this

    fun <T> getInstance(o: Any, i: Int): T? {
        try {
            return ((o.javaClass
                    .genericSuperclass as ParameterizedType).actualTypeArguments[i] as Class<T>)
                    .newInstance()
        } catch (e: InstantiationException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: ClassCastException) {
            e.printStackTrace()
        }

        return null
    }

    override fun baseShowLoading() {
        if (mPresenter != null && getmViewLoading() != null) {
            if (getmViewLoading()?.isShowing as Boolean) {
                getmViewLoading()?.dismiss()
            }
            getmViewLoading()?.show()
        }
    }

    override fun baseHideLoading() {
        if (mPresenter != null && getmViewLoading() != null) {
            if (getmViewLoading()?.isShowing as Boolean) {
                getmViewLoading()?.dismiss()
            }
        }
    }
}
